package com.example.yx.demo27;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.mock.http.MockHttpInputMessage;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class A27 {

    public static void main(String[] args) throws IOException {
//        test1();
    test2();

    }


    @ResponseBody

    public User user() {
        return null;
    }

//转JSON
    public static void test1() throws IOException {
        MockHttpOutputMessage message = new MockHttpOutputMessage();
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        if (messageConverter.canWrite(User.class, MediaType.APPLICATION_JSON)) {
            messageConverter.write(new User("张三",18),MediaType.APPLICATION_JSON,message);
            System.out.println(message.getBodyAsString());
        }
    }
    //转XML
    public static void test2() throws IOException {
        MockHttpOutputMessage message = new MockHttpOutputMessage();
        MappingJackson2XmlHttpMessageConverter messageConverter = new MappingJackson2XmlHttpMessageConverter();
        if (messageConverter.canWrite(User.class, MediaType.APPLICATION_XML)) {
            messageConverter.write(new User("李四",20),MediaType.APPLICATION_XML,message);
            System.out.println(message.getBodyAsString());
        }
    }
    //Json转消息
    public static void test3() throws IOException {}
    public static void test4() throws IOException {}
    public static class User{
        private String name;
        private int age;

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @JsonCreator
        public User(@JsonProperty("name") String name,@JsonProperty("age") int age) {
            this.name = name;
            this.age = age;
        }
    }
}
